<template>
  <div>
    <div>
      <el-tabs
        v-model="editableTabsValue"
        type="border-card"
        @tab-remove="removeTab"
      >
        <el-tab-pane
          :closable="item.closable"
          v-for="(item, index) in tabPaneList"
          :name="item.name"
          :key="index"
          :label="item.label"
        >
          <div v-if="item.name == 'list'">
            <div>
              <el-form
                :inline="true"
                :model="formSearch"
                class="demo-form-inline"
              >
                <el-form-item label="资讯标题">
                  <el-input
                    v-model="formSearch.title"
                    placeholder="请输入资讯标题"
                  ></el-input>
                </el-form-item>
                <el-form-item label="发布者ID">
                  <el-input
                    v-model="formSearch.adminid"
                    placeholder="请输入发布者ID"
                  ></el-input>
                </el-form-item>
                <el-form-item label="资讯作者">
                  <el-input
                    v-model="formSearch.author"
                    placeholder="请输入资讯作者"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchClick"
                    >查询</el-button
                  >
                  <el-button type="danger" @click="clearClick">清空</el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table :data="tableData" stripe border style="width: 100%">
              <el-table-column prop="id" label="ID" sortable width="80px">
              </el-table-column>
              <el-table-column prop="adminid" label="发布者ID" width="120px">
              </el-table-column>
              <el-table-column
                prop="title"
                label="资讯标题"
                sortable
                width="200px"
              >
              </el-table-column>
              <el-table-column prop="hover" label="资讯描述" sortable>
              </el-table-column>
              <el-table-column prop="image_url" label="资讯封面" width="180">
                <template slot-scope="scope">
                  <el-image :src="baseURL + scope.row.cover_img"></el-image>
                </template>
              </el-table-column>
              <el-table-column
                prop="author"
                label="资讯作者"
                sortable
                width="100px"
              >
              </el-table-column>
              <el-table-column
                prop="create_time"
                sortable
                label="注册时间"
                width="180px"
              >
              </el-table-column>
              <el-table-column prop="tag" label="状态" sortable width="80px">
                <template slot-scope="scope">
                  <el-tag
                    :type="infotype(scope.row.tag).style"
                    disable-transitions
                    >{{ infotype(scope.row.tag).label }}</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column label="是否显示" width="100">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.is_show"
                    :active-value="1"
                    :inactive-value="0"
                    @change="(val) => swichEvent(val, scope.row.id)"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作">
                <template
                  slot-scope="scope"
                  v-if="$store.state.user && $store.state.user.admin_grade > 1"
                >
                  <el-button
                    type="primary"
                    plain
                    @click="updateClick(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    plain
                    @click="deleteClick(scope.row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              layout="prev, pager, next"
              :page-size="10"
              :current-page="pagenum"
              @current-change="pageChange"
              :total="total"
            >
            </el-pagination>
          </div>

          <div v-if="item.name == 'add'">
            <el-form
              ref="addRuleForm"
              :rules="rules"
              :model="addForm"
              label-position="right"
              label-width="80px"
            >
              <el-form-item label="标题" prop="title">
                <el-input v-model="addForm.title" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="资讯简述" prop="hover">
                <el-input v-model="addForm.hover" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="作者署名" prop="author">
                <el-input
                  v-model="addForm.author"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="状态" prop="tag">
                <el-select v-model="addForm.tag">
                  <el-option
                    v-for="(item, index) in ReplayType"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="封面图" prop="cover_img">
                <el-button
                  style="margin-bottom: 5px"
                  type="primary"
                  @click="openMapClick"
                  >选择一张广告图</el-button
                >
                <el-input v-model="addForm.cover_img" disabled></el-input>
              </el-form-item>
              <el-form-item label="文章内容" prop="content">
                <quill-editor
                  ref="myAddEditor"
                  class="editor-wrap"
                  v-model="addForm.content"
                  :options="editorOption"
                >
                </quill-editor>
              </el-form-item>
            </el-form>
            <div style="text-align: center">
              <el-button>取 消</el-button>
              <el-button type="primary" @click="addUserEvent">确 定</el-button>
            </div>
          </div>

          <div v-if="item.name == 'edit'">
            <el-form
              ref="upRuleForm"
              :rules="rules"
              :model="updateForm"
              label-position="right"
              label-width="80px"
            >
              <el-form-item label="资讯ID" prop="id">
                <el-input
                  v-model="updateForm.id"
                  disabled
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="资讯标题" prop="title">
                <el-input
                  v-model="updateForm.title"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="资讯简述" prop="hover">
                <el-input
                  v-model="updateForm.hover"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="作者署名" prop="author">
                <el-input
                  v-model="updateForm.author"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="类型" prop="tag">
                <el-select v-model="updateForm.tag">
                  <el-option
                    v-for="item in ReplayType"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="封面图" prop="cover_img">
                <el-button
                  style="margin-bottom: 5px"
                  type="primary"
                  @click="openMapClick"
                  >选择一张广告图</el-button
                >
                <el-input v-model="updateForm.cover_img" disabled></el-input>
              </el-form-item>
              <el-form-item label="文章内容" prop="content">
                <quill-editor
                  ref="myEditEditor"
                  class="editor-wrap"
                  v-model="updateForm.content"
                  :options="editorOption"
                >
                </quill-editor>
              </el-form-item>
            </el-form>
            <div style="text-align: center">
              <el-button @click="removeTab('edit')">取 消</el-button>
              <el-button type="primary" @click="updateUserEvent"
                >确 定</el-button
              >
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <MapSelect ref="mapPop" @mapselectEvent="mapselectEvent"></MapSelect>
    <MapSelect ref="artPop" @mapselectEvent="artselectEvent"></MapSelect>
  </div>
</template>

<script>
import { quillEditor, Quill } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { ImageDrop } from "quill-image-drop-module";
import ImageResize from "quill-image-resize-module";
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize);

import menu from "@/assets/menu.json";
import {
  addInformation,
  editArticleList,
  editInformation,
  getInformation,
} from "@/request";
import MapSelect from "@/components/MapSelect";
export default {
  name: "List",
  components: {
    MapSelect,
    quillEditor,
  },
  data() {
    return {
      rules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        hover: [{ required: true, message: "请输入资讯简述", trigger: "blur" }],
        author: [
          { required: true, message: "请选择资讯作者", trigger: "blur" },
        ],
        cover_img: [
          { required: true, message: "请选择文章封面图", trigger: "blur" },
        ],
        tag: [
          { required: true, message: "请选择文章的发布状态", trigger: "blur" },
        ],
      },
      tableData: [],
      updateForm: {},
      total: 0,
      pagenum: 1,
      formSearch: {
        title: null,
        author: null,
        adminid: null,
      },
      editableTabsValue: "list",
      tabPaneList: [
        {
          label: "资讯列表",
          name: "list",
          closable: false,
        },
        {
          label: "添加资讯",
          name: "add",
          closable: false,
        },
      ],
      addForm: {
        adminid: this.$store.state.token.adminid,
        title: null,
        hover: null,
        author: null,
        tag: null,
        cover_img: null,
        content: null,
      },
      ReplayType: menu.ReplayType,
      editorOption: {
        placeholder: "请输入文章内容...",
        modules: {
          toolbar: {
            container: [
              [{ color: [] }, { background: [] }],
              ["bold", "italic", "underline", "strike"],
              [{ size: ["small", false, "large"] }],
              [{ list: "ordered" }, { list: "bullet" }],
              ["link", "image"],
              [{ align: [] }],
            ],
            handlers: {
              image: (val) => {
                if (val) {
                  this.$refs.artPop.showMapSelect();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        },
      },
    };
  },
  computed: {
    infotype() {
      return function (value) {
        let item = menu.ReplayType.find((o) => o.value == value);
        return item;
      };
    },
  },
  created() {
    this.getinformation();
  },
  methods: {
    openMapClick() {
      this.$refs.mapPop.showMapSelect();
    },
    async getinformation() {
      this.formSearch["pagenum"] = this.pagenum;
      let data = await getInformation(this.formSearch);
      if (data.code != 200) return this.$message.error(data.message);
      this.tableData = data.data.list;
      this.total = data.data.total;
    },
    pageChange(val) {
      this.pagenum = val;
      this.getinformation();
    },
    init() {
      this.pagenum = 1;
      this.total = 0;
    },
    addUserEvent() {
      let that = this;
      this.$refs["addRuleForm"][0].validate(async (valid) => {
        if (!valid) {
          return false;
        }
        let data = await addInformation(that.addForm);
        if (data.code != 200) return this.$message.error(data.message);
        this.$message.success("添加成功!");
        this.init();
        this.getinformation();
        this.addForm = {
          title: null,
          hover: null,
          author: null,
          tag: null,
          cover_img: null,
          content: null,
        };
      });
    },
    removeTab(targetName) {
      let tabs = this.tabPaneList;
      let activeName = this.editableTabsValue; //获取当前选中
      if (activeName === targetName) {
        //关闭=选中
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1]; //前后或后面
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.tabPaneList = tabs.filter((tab) => tab.name !== targetName);
    },
    mapselectEvent(value) {
      if (this.editableTabsValue == "add")
        this.addForm["cover_img"] = value.length && value[0].filepath;
      if (this.editableTabsValue == "edit")
        this.updateForm["cover_img"] = value.length && value[0].filepath;
    },
    artselectEvent(value) {
      let quill = null;
      if (this.editableTabsValue == "add")
        quill = this.$refs.myAddEditor[0].quill;
      if (this.editableTabsValue == "edit")
        quill = this.$refs.myEditEditor[0].quill;
      //获取光标所在位置
      let length = quill.selection.savedRange.index;
      //插入图片
      quill.insertEmbed(length, "image", this.baseURL + value[0].filepath);
      quill.setSelection(length + 1);
    },
    updateClick(item) {
      this.updateForm = {
        id: item.id,
        title: item.title,
        hover: item.hover,
        author: item.author,
        tag: item.tag,
        cover_img: item.cover_img,
        content: item.content,
      };
      this.addTab();
    },
    addTab() {
      this.removeTab("edit");
      this.tabPaneList.push({
        label: "编辑资讯",
        name: "edit",
        closable: true,
      });
      this.editableTabsValue = "edit";
    },
    async updateUserEvent() {
      let that = this;
      this.$refs["upRuleForm"][0].validate(async (valid) => {
        if (!valid) {
          return false;
        }
        let data = await editInformation(this.updateForm);
        if (data.code != 200) return this.$message.error(data.message);
        this.$message.success(data.message);
        this.init();
        this.getinformation();
      });
    },
    async swichEvent(val, id) {
      let data = await editInformation({ id, is_show: val });
      if (data.code != 200) return this.$message.error(data.message);
      this.$message.success(data.message);
      this.getinformation();
    },
    deleteClick(id) {
      console.log(id);
      this.$confirm("您将删除该资讯, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let data = await editInformation({ id, is_delete: 1 });
          if (data.code != 200) return this.$message.error(data.message);
          this.$message.success(data.message);
          this.init();
          this.getinformation();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    searchClick() {
      this.init();
      this.getinformation();
    },
    clearClick() {
      this.formSearch = {
        title: null,
        adminid: null,
        author: null,
      };
      this.init();
      this.getinformation();
    },
  },
};
</script>

<style scoped>
/deep/ .editor-wrap .ql-container {
  min-height: 300px;
}
</style>
